package com.renfei.multimediatask.ui.task3;

import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import com.renfei.multimediatask.R;
import com.renfei.multimediatask.base.BaseActivity;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PreviewSurfaceActivity extends BaseActivity implements SurfaceHolder.Callback {

    @BindView(R.id.surfaceView)
    SurfaceView surfaceView;


    private int cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;//摄像头ID


    private Camera camera;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_preview_surface;
    }


    @Override
    protected void initListener() {

        surfaceView.getHolder().addCallback(this);
        initCamera();
    }

    private void initCamera() {
        // 打开摄像头并将展示方向旋转90度
        camera = Camera.open();
        camera.setDisplayOrientation(90);

        /**
         * 通过设置parameters 配置数据回调格式为NV21
         */
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewFormat(ImageFormat.NV21);
        camera.setParameters(parameters);

        /**
         * 设置预览回调数据
         */
        camera.setPreviewCallback(new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] data, Camera camera) {

//                loge("camera    PreviewCallback    ", new String(data).toString());
            }
        });
    }

   //@Override
   //protected void onStop() {
   //    super.onStop();
   //    if (null != camera) {
   //        camera.stopPreview();
   //        camera.setPreviewCallback(null);
   //        camera.release();
   //    }
   //}



    @Override
    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
        try {

            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
       if (null != camera) {
           camera.stopPreview();
           camera.setPreviewCallback(null);
           camera.release();
       }
    }
}
